package controllers

import (
	"docter/cathe"
	"docter/models"
	"encoding/json"
	beego "github.com/beego/beego/v2/server/web"
)

type DocterController struct {
	beego.Controller
}

func (c *DocterController) Add() {
	name := c.GetString("name")
	tel := c.GetString("tel")
	types := c.GetString("types")
	price, _ := c.GetFloat("price")
	file, header, err := c.GetFile("img")
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "请选择要上传的图片",
		}
		c.ServeJSON()
		return
	}
	defer file.Close()
	path := "static/img/" + header.Filename
	c.SaveToFile("img", path)
	docter := models.Docter{
		Img:   "http://127.0.0.1:8080/" + path,
		Name:  name,
		Tel:   tel,
		Types: types,
		Price: price,
	}
	err = docter.Create()
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "添加失败",
		}
		c.ServeJSON()
		return
	}
	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "添加成功",
	}
	c.ServeJSON()
	return
}
func (c *DocterController) List() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	var dockter []*models.Docter
	catheData := cathe.Rdb.Get(cathe.Ctx, "dockter_list").Val()
	if catheData == "" {
		var dockter models.Docter
		Data, _ := dockter.List()
		jsonData, _ := json.Marshal(Data)
		cathe.Rdb.Set(cathe.Ctx, "dockter_list", jsonData, 0)
	} else {
		json.Unmarshal([]byte(catheData), &dockter)
	}

	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "获取成功",
		"data": &dockter,
	}
	c.ServeJSON()
	return
}
